package com.bds.tjj.service;

import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.bds.tjj.model.YearAreaData;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;
import org.springframework.stereotype.Service;

import com.bds.tjj.model.PropIndex;
import com.bds.tjj.model.YearData;
import com.bds.tjj.utils.Const;

/**
 * Created by guoyu on 2018/1/29.
 */
@Service
public class YearSumService {
    private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(YearSumService.class);
    private static final DecimalFormat df = new DecimalFormat("#.0");

    @Resource
    private NutDao dao;

    @Resource
    private UserService userService;

    public YearData getYearNum(String type) throws Exception {
        type = URLDecoder.decode(type, "utf-8");
        List<YearData> yearDataList = dao.query(YearData.class, Cnd.where("prop", "=", type).and("data", "is not", null)
                .and("data", "<>", "").limit(1, 2).orderBy("yy", "desc"));
        if (yearDataList.size() > 0) {
            YearData yearData = yearDataList.get(0);
            YearData yearDataAgo = yearDataList.get(1);
            PropIndex pi = dao.fetch(PropIndex.class, Cnd.where("prop", "=", type));
            if (pi != null) {
                yearData.setUnit(pi.getUnit());
            }
            if (yearData.getData() != null && yearData.getData().contains(".")) {
                if (yearData.getData().split("\\.")[1].length() > Const.decimal_num) {
                    yearData.setData(df.format(Double.parseDouble(yearData.getData())));
                }
            }

            // 计算增长率
            try {
                if (yearData.getYy() - yearDataAgo.getYy() == 1) {
                    if (yearData.getData() != null && (!yearData.getData().equals(""))) {
                        double a = Double.parseDouble(yearData.getData()) - Double.parseDouble(yearDataAgo.getData());
                        double b = Math.abs(Double.parseDouble(yearDataAgo.getData()));
                        double r = (a * 1.0 / b) * 100;
                        yearData.setYya(Double.parseDouble(df.format(r)));
                        yearData.setAbs(Double.parseDouble(df.format(a)));
                    } else {
                        yearData.setYya(null);
                        yearData.setAbs(null);
                    }
                } else {
                    yearData.setYya(null);
                    yearData.setAbs(null);
                }
            } catch (Exception e) {
                yearData.setYya(null);
                yearData.setAbs(null);
            }
            return yearData;
        } else {
            return new YearData();
        }

    }

    public YearData getLastYear() throws Exception {

        List<YearData> ls = dao.query(YearData.class, Cnd.NEW().limit(1, 1).desc("yy"));
        if (ls != null && ls.size() > 0) {
            return ls.get(0);
        } else {
            return null;
        }
    }

    public List<YearData> getYearTips() throws Exception {

        List<PropIndex> ps = userService.getDataSelect("year");
        List<YearData> ys = new ArrayList<YearData>();
        for (int i = 0; i < ps.size(); i++) {
            PropIndex pi = ps.get(i);
            YearData yy = this.getYearNum(pi.getProp());
            if (yy != null) {
                if (i % 4 == 0) {
                    yy.setStyle_class("success");
                } else if (i % 4 == 1) {
                    yy.setStyle_class("info");
                } else if (i % 4 == 2) {
                    yy.setStyle_class("important");
                } else if (i % 4 == 3) {
                    yy.setStyle_class("warning");
                }
                ys.add(yy);
            } else {
                LOGGER.error("没有此指标:" + pi.getCn_name());
            }

        }

        return ys;

    }

    public List<YearData> getYearTips(String tabName) throws Exception {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -7);
        Date lastdate = cal.getTime();
        List<PropIndex> ps = userService.getDataSelect("year", tabName);
        List<YearData> ys = new ArrayList<YearData>();
        for (int i = 0; i < ps.size(); i++) {
            PropIndex pi = ps.get(i);
            if (pi.getIs_area() == 1) {
                continue;
            }
            YearData yy = this.getYearNum(pi.getProp());


            if (yy != null) {
                yy.setEn_name(pi.getView_name());
                yy.setUnit(pi.getUnit());
                if (yy.getCreate_time().after(lastdate)) {
                    yy.setIsnew("1");
                } else {
                    yy.setIsnew("0");
                }
                if (i % 4 == 0) {
                    yy.setStyle_class("success");
                } else if (i % 4 == 1) {
                    yy.setStyle_class("info");
                } else if (i % 4 == 2) {
                    yy.setStyle_class("important");
                } else if (i % 4 == 3) {
                    yy.setStyle_class("warning");
                }
                ys.add(yy);
            } else {
                LOGGER.error("没有此指标:" + pi.getCn_name());
            }

        }

        return ys;

    }

    public List<YearData> getYearTrend(String type, int startTime, int endTime) throws Exception {
        type = URLDecoder.decode(type, "utf-8");
        List<YearData> list = dao.query(YearData.class,
                Cnd.where("prop", "=", type).and("yy", ">=", startTime).and("yy", "<=", endTime).orderBy("yy", "desc"));

        Collections.reverse(list);

        PropIndex prop = new PropIndex();
        if (list.size() > 0) {
            prop = dao.fetch(PropIndex.class, Cnd.where("prop", "=", list.get(0).getProp()));
        }

        String preData = null;
        for (int i = 0; i < list.size(); i++) {
            YearData yearData = list.get(i);

            yearData.setUnit(prop.getUnit());
            yearData.setView_name(prop.getView_name());

            // 需要计算增长率时才去计算
            if (prop.getIf_rate() == 0) {
                if (i == 0) {
                    yearData.setYya(0.0);
                } else {
                    if (preData != null && (!preData.equals(""))) {
                        if (yearData.getData() != null && (!yearData.getData().equals(""))) {
                            double a = Double.parseDouble(yearData.getData()) - Double.parseDouble(preData);
                            double b = Math.abs(Double.parseDouble(preData));
                            double r = (a * 1.0 / b) * 100;
                            yearData.setYya(Double.parseDouble(df.format(r)));
                        }
                    } else {
                        yearData.setYya(0.0);
                    }
                }
            }

            if (yearData.getData() == null) {
                continue;
            }

            if (prop != null) {
                yearData.setEn_name(prop.getEn_name());
                yearData.setIs_area(prop.getIs_area());
            }
            // 是否是小数
            if (yearData.getData().contains(".")) {
                // 小数点后是否大于4位
                if (yearData.getData().split("\\.")[1].length() > Const.decimal_num) {
                    yearData.setData(df.format(Double.parseDouble(yearData.getData())));
                }
            }

            if (yearData.getData() != null) {
                if (!yearData.getData().equals("")) {
                    preData = yearData.getData();
                }
            }
        }

        Collections.reverse(list);

        return list;
    }

    public List<YearAreaData> getYearAreaTrend(String type, int startTime, int endTime, String areaId) throws Exception {
        type = URLDecoder.decode(type, "utf-8");
        List<YearAreaData> list = dao.query(YearAreaData.class,
                Cnd.where("prop", "=", type)
                        .and("yy", ">=", startTime).and("yy", "<=", endTime)
                        .and("area_code", "=", areaId)
                        .orderBy("yy", "desc"));

        Collections.reverse(list);

        PropIndex prop = new PropIndex();
        if (list.size() > 0) {
            prop = dao.fetch(PropIndex.class, Cnd.where("prop", "=", list.get(0).getProp()));
        }

        String preData = null;
        for (int i = 0; i < list.size(); i++) {
            YearAreaData yearAreaData = list.get(i);

            yearAreaData.setUnit(prop.getUnit());
            yearAreaData.setView_name(prop.getView_name());

            // 需要计算增长率时才去计算
            if (prop.getIf_rate() == 0) {
                if (i == 0) {
                    yearAreaData.setYya(0.0);
                } else {
                    if (preData != null && (!preData.equals(""))) {
                        if (yearAreaData.getData() != null && (!yearAreaData.getData().equals(""))) {
                            double a = Double.parseDouble(yearAreaData.getData()) - Double.parseDouble(preData);
                            double b = Math.abs(Double.parseDouble(preData));
                            double r = (a * 1.0 / b) * 100;
                            yearAreaData.setYya(Double.parseDouble(df.format(r)));
                        }
                    } else {
                        yearAreaData.setYya(0.0);
                    }
                }
            }

            if (yearAreaData.getData() == null) {
                continue;
            }

            if (prop != null) {
                yearAreaData.setEn_name(prop.getEn_name());
                yearAreaData.setIs_area(prop.getIs_area());
            }
            // 是否是小数
            if (yearAreaData.getData().contains(".")) {
                // 小数点后是否大于4位
                if (yearAreaData.getData().split("\\.")[1].length() > Const.decimal_num) {
                    yearAreaData.setData(df.format(Double.parseDouble(yearAreaData.getData())));
                }
            }

            if (yearAreaData.getData() != null) {
                if (!yearAreaData.getData().equals("")) {
                    preData = yearAreaData.getData();
                }
            }
        }

        Collections.reverse(list);

        return list;
    }

    public List<YearAreaData> getYearAreaTips(String tabName, String areaId) throws Exception {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -7);
        Date lastdate = cal.getTime();
        List<PropIndex> ps = userService.getDataAreaSelect("year", tabName);
        List<YearAreaData> ys = new ArrayList<YearAreaData>();
        for (int i = 0; i < ps.size(); i++) {
            PropIndex pi = ps.get(i);
            YearAreaData yy = this.getYearAreaNum(pi.getProp(), areaId);


            if (yy != null) {
                yy.setEn_name(pi.getView_name());
                yy.setUnit(pi.getUnit());
                if (yy.getCreate_time().after(lastdate)) {
                    yy.setIsnew("1");
                } else {
                    yy.setIsnew("0");
                }
                if (i % 4 == 0) {
                    yy.setStyle_class("success");
                } else if (i % 4 == 1) {
                    yy.setStyle_class("info");
                } else if (i % 4 == 2) {
                    yy.setStyle_class("important");
                } else if (i % 4 == 3) {
                    yy.setStyle_class("warning");
                }
                ys.add(yy);
            } else {
                LOGGER.error("没有此指标:" + pi.getCn_name());
            }

        }

        return ys;

    }

    public YearAreaData getYearAreaNum(String type, String areaId) throws Exception {
        type = URLDecoder.decode(type, "utf-8");
        List<YearAreaData> yearDataList = dao.query(YearAreaData.class,
                Cnd.where("prop", "=", type).and("data", "is not", null)
                        .and("data", "<>", "").and("area_code", "=", areaId)
                        .limit(1, 2).orderBy("yy", "desc"));
        if (yearDataList.size() > 0) {
            YearAreaData yearData = yearDataList.get(0);
            YearAreaData yearDataAgo = yearDataList.get(1);
            PropIndex pi = dao.fetch(PropIndex.class, Cnd.where("prop", "=", type));
            if (pi != null) {
                yearData.setUnit(pi.getUnit());
            }
            if (yearData.getData() != null && yearData.getData().contains(".")) {
                if (yearData.getData().split("\\.")[1].length() > Const.decimal_num) {
                    yearData.setData(df.format(Double.parseDouble(yearData.getData())));
                }
            }

            // 计算增长率
            try {
                if (yearData.getYy() - yearDataAgo.getYy() == 1) {
                    if (yearData.getData() != null && (!yearData.getData().equals(""))) {
                        double a = Double.parseDouble(yearData.getData()) - Double.parseDouble(yearDataAgo.getData());
                        double b = Math.abs(Double.parseDouble(yearDataAgo.getData()));
                        double r = (a * 1.0 / b) * 100;
                        yearData.setYya(Double.parseDouble(df.format(r)));
                    } else {
                        yearData.setYya(null);
                    }
                } else {
                    yearData.setYya(null);
                }
            } catch (Exception e) {
                yearData.setYya(null);
            }
            return yearData;
        } else {
            return new YearAreaData();
        }

    }
}
